<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Models\Company;

class AuthRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'X-Company-Id' => 'required|exists:companies,company_id',
            'X-Nonce-Str' => 'required',
            'X-Sign' => 'required',
        ];
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {

            if (!$this->isValidSign()) {

                $validator->errors()->add('sign', 'sign was wrong');
            }
        });
    }

    private  function isValidSign() {
        $company = Company::active()->companyId($this->input('X-Company-Id'))->first();
        return hash("sha256", $this->input('X-Nonce-Str').'&'.$company->api_authentication_key) == $this->input('X-Sign');
    }
}
